import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:grasp_flutter_app/utils/dao/bill_header_dao.dart';
import 'package:grasp_flutter_app/utils/dao/bill_xsck_dao.dart';
import 'package:grasp_flutter_app/utils/model/bill_xsck.dart';
import 'package:grasp_flutter_app/utils/utils.dart';
import 'package:grasp_flutter_app/utils/view/ListItem.dart';

class BillXSCKPage extends StatefulWidget {
  static const String name = "开销售出库单";

  const BillXSCKPage({Key key, this.billData}) : super(key: key);
  final BillXSCKItem billData;

  @override
  State<StatefulWidget> createState() {
    return _BillXSCKPageState();
  }
}

class _BillXSCKPageState extends State<BillXSCKPage> {
  BillXSCKItem _data;

  @override
  void initState() {
    super.initState();
    _data = widget.billData;
    if (_data == null)
      _data = BillXSCKItem({});
  }

  @override
  Widget build(BuildContext context) {
    return Common.buildTopScaffold(
      context,
      title: buildTitle(), // Text("开销售出库单"),
      body: buildBody(),
    );
  }

  Widget buildTitle() {
    return GestureDetector(
      child: IconText(text: BillXSCKPage.name, icon: Icon(Icons.help_outline), useWrap: true, overflow: TextOverflow.ellipsis, iconLast: true),
      onTap: () {
        Utils.toast("${BillXSCKPage.name}帮助");
      },
    );
  }

  final List<int> _filterHeader = [0, 1, 2, 3, 4, 5, 6, 7];

  Widget buildBody() {
    return Column(
      children: <Widget>[
        Expanded(
          child: Container(
            child: ListView(
              padding: EdgeInsets.zero,
              children: buildListItems(),
            ),
          ),
        ),
        buildBottomBar(),
      ],
    );
  }

  Widget buildBottomBar() {
    return Material(
      elevation: 32.0,
      color: Styles.white,
      child: Row(
        children: <Widget>[
          buildBottomBarItem(Text("调申请单"), border: false, onTap: (){}),
          buildBottomBarItem(Text(Utils.getLocale(context).share), onTap: (){}),
          buildBottomBarItem(Text(Utils.getLocale(context).print), onTap: (){}),
          buildBottomBarItem(Text("保存"), onTap: (){}),
          buildBottomBarItem(Text("过账", style: TextStyle(color: Styles.primaryValue)), onTap: (){}),
        ],
      ),
    );
  }

  Widget buildBottomBarItem(Widget child, {VoidCallback onTap, bool border = true}) {
    return Expanded(
      child: InkWell(
        child: Container(
          height: 30.0,
          decoration: BoxDecoration(
            border: border ? const Border(left: BorderSide(width: 0.5, color: Styles.lineColor)) : null
          ),
          margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
          alignment: Alignment.center,
          child: DefaultTextStyle.merge(child: child, style: TextStyle(
              fontSize: Styles.textSmallSize,
              color: Styles.mainTextColor
          )),
        ),
        onTap: onTap,
      ),
    );
  }

  List<Widget> buildListItems() {
    List<Widget> items = [];
    items.add(
        buildListTitleItem(title: Text("表头信息"), trailing: IconButton(icon: Icon(Icons.settings), onPressed: () {
          showSettingHeader();
        })),
    );
    List<BillHeaderItem> data = BillHeaderDao.getHeaders(onContainId: _filterHeader);
    BillHeaderItem _last = data.last;
    data.forEach((item) {
      if (!item.visible) return;
      items.add(buildHeaderItem(item, isLast: item == _last, onTap: () {
        showHeaderItemValue(item);
      }));
    });
    items.add(
      buildListTitleItem(title: Text("商品信息"), right: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        IconButton(icon: Icon(Icons.refresh), onPressed: () {}),
        IconButton(icon: Icon(Icons.fullscreen), onPressed: () {}),
        IconButton(icon: Icon(Icons.credit_card), onPressed: () {}),
        IconButton(icon: Icon(Icons.add, color: Styles.primaryValue), onPressed: () {}),
      ])),
    );
    items.add(
      buildListTitleItem(title: Text("费用信息"), right: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        IconButton(icon: Icon(Icons.add, color: Styles.primaryValue), onPressed: () {}),
      ])),
    );
    items.add(
      buildListTitleItem(title: Text("收款信息"), right: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        IconButton(icon: Icon(Icons.add, color: Styles.primaryValue), onPressed: () {}),
      ])),
    );
    items.add(
      buildListTitleItem(title: Text("附件信息"), right: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        IconButton(icon: Icon(Icons.delete_outline, color: Styles.primaryValue), onPressed: () {}),
      ])),
    );

    items.add(
      buildListTitleItem(title: Text("物流信息"), right: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
      ])),
    );
    items.add(buildChildItem("收货地址", null, null, onTap: () {}));
    items.add(buildChildItem("物流单号", null, null, padding: EdgeInsets.only(left: 8.0), child: Container(
        height: 50.0,
        width: double.infinity,
        child: Row(
          children: <Widget>[
            Expanded(
              child: TextField(
                controller: TextEditingController(),
                maxLines: 2,
                style: Styles.smallText,
                textAlignVertical: TextAlignVertical.center,
                decoration: InputDecoration(
                  hintText: "请输入物流单号, 多个单号换行隔开",
                  hintStyle: Styles.smallSubText,
                  border: OutlineInputBorder(borderSide: BorderSide(width: 0.5, color: Styles.lineColor), gapPadding: 8.0),
                  focusedBorder: OutlineInputBorder(borderSide: BorderSide(width: 0.5, color: Styles.primaryValue), gapPadding: 8.0),
                  contentPadding: const EdgeInsets.only(top: 8.0, left: 6.0, bottom: 4.0, right: 6.0),
                ),
              ),
            ),
            IconButton(icon: Icon(Icons.fullscreen), onPressed: () {}),
            IconButton(icon: Icon(Icons.more_horiz), onPressed: () {}),
          ],
        ),
      )));
    items.add(buildChildItem("物流公司", null, "请选择物流公司", onTap: () {}));
    items.add(buildChildItem("代收", null, "请选择代收单位", isLast: true, onTap: () {}));

    items.add(SizedBox(height: 32.0));
    return items;
  }

  Widget buildListTitleItem({Widget title, Widget right, Widget trailing}) {
    return Container(
      margin: const EdgeInsets.only(top: 12.0),
      child: ListItem(title: Row(children: <Widget>[
        Container(
          width: 5.0,
          height: Styles.textSmallSize + 3.0,
          margin: EdgeInsets.only(top: 1.0),
          color: Styles.primaryValue,
        ),
        SizedBox(width: 8.0),
        title ?? SizedBox(),
        right == null && trailing == null ? SizedBox() : Expanded(
          child: Material(
            color: Colors.transparent,
            child: Container(
              alignment: Alignment.centerRight,
              child: right ?? trailing,
            ),
          ),
        )
      ]), contentPadding: EdgeInsets.only(left: 16.0, right: 4.0)),
      decoration: BoxDecoration(
        color: Styles.white,
        border: Border(bottom: BorderSide(color: Styles.lineColor, width: Styles.lineSize))
      ),
    );
  }

  Widget buildHeaderItem(BillHeaderItem item, {bool isLast = false, VoidCallback onTap}) {
    return buildChildItem(item.name, getItemValue(item.id), item.hint, isLast: isLast, onTap: onTap);
  }

  Widget buildChildItem(String title, String value, String hint, {bool isLast = false, Widget child, EdgeInsetsGeometry padding, VoidCallback onTap}) {
    return Material(
      color: Styles.white,
      child: InkWell(
        child: Padding(
          padding: isLast ? EdgeInsets.zero : const EdgeInsets.only(left: 16.0, right: 16.0),
          child: Container(
            padding: isLast ? const EdgeInsets.only(left: 16.0, right: 16.0) : EdgeInsets.zero,
            child: ListItem(
              contentPadding: padding ?? const EdgeInsets.only(left: 8.0, right: 8.0),
              leading: SizedBox(width: 70.0, child: Text(title)),
              title: child ?? Text(value ?? hint ?? "请输入$title", style: value == null || value.isEmpty ? Styles.smallSubText : Styles.smallText),
              trailing: child == null ? Icon(Icons.keyboard_arrow_right, size: 16.0) : null,
            ),
            decoration: BoxDecoration(
                border: Border(bottom: BorderSide(color: Styles.lineColor, width: Styles.lineSize))
            ),
          ),
        ),
        onTap: onTap,
      ),
    );
  }

  String getItemValue(int id) {
    switch (id) {
      case 0: return _data.id;
      case 3: return Utils.dateToStr(_data.date ?? DateTime.now(), true);
      default:
        return null;
    }
  }

  showSettingHeader() async {
    await BillHeaderDao.load();
    showDialog(context: context, builder: (context) {
      HeadersListView list = HeadersListView(data: BillHeaderDao.getHeaders(onContainId: null));
      return AlertDialog(
        title: Text("表头显示"),
        content: list,
        actions: <Widget>[
          FlatButton(child: Text("取消"), onPressed: () {Navigator.pop(context);}),
          FlatButton(child: Text("确认"), onPressed: () {
            for (int i=0; i<list.data.length; i++) {
              list.data[i].visible = list.visibleState[i];
            }
            BillHeaderDao.save();
            Navigator.pop(context);
            setState(() {});
          })
        ],
      );
    });
  }

  showHeaderItemValue(BillHeaderItem item) async {

  }
}

class HeadersListView extends StatefulWidget {
  HeadersListView({Key key, this.data}) : super(key: key);
  final List<BillHeaderItem> data;
  List<bool> visibleState = [];
  @override
  State<StatefulWidget> createState() {
    return _HeadersListViewState();
  }
}

class _HeadersListViewState extends State<HeadersListView> {

  @override
  void initState() {
    super.initState();

    widget.visibleState.clear();
    widget.data.forEach((v) {
      widget.visibleState.add(v.visible);
    });
  }

  @override
  Widget build(BuildContext context) {
    print(widget.data);
    List<Widget> items = [];
    for (int i=0; i<widget.data.length; i++) {
      items.add(ListItem(leading: Icon(widget.visibleState[i] ? Icons.check_box : Icons.check_box_outline_blank), title: Text(widget.data[i].name), dense: true, onTap: () {
        setState(() {
          widget.visibleState[i] = !widget.visibleState[i];
        });
      }));
    }
    return SingleChildScrollView(
      child: ListBody(
        children: items,
      ),
    );
  }
}